<!DOCTYPE html>
<html>

<head>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <style>
        /* Style the buttons */
        .btn {
            border: none;
            outline: none;
            padding: 10px 16px;
            background-color: #f1f1f1;
            cursor: pointer;
            font-size: 18px;
        }

        /* Style the active class, and buttons on mouse-over */
        .active,
        .btn:hover {
            background-color: #666;
            color: white;
        }
    </style>
</head>

<body>

    <h1>Active Button</h1>
    <p>Highlight the active/current (pressed) button.</p>

    <div id="myDIV">
        <button class="btn">1</button>
        <button class="btn active">2</button>
        <button class="btn">3</button>
        <button class="btn">4</button>
        <button class="btn">5</button>
    </div>


    <h1>     必知必会                      </h1>


    <xmp style="font-size: 22px; font-weight: bolder;  margin-bottom: 66px;  color: black;  font-family: '微软雅黑';">
        var header = document.getElementById("myDIV");
        var btns = header.getElementsByClassName("btn");

        //  循环绑定 click 事件: 
        for (var i = 0; i < btns.length; i++) {
            btns[i].addEventListener("click", function () {
                var current = document.getElementsByClassName("active");
                current[0].className = current[0].className.replace(" active", "");
                this.className += " active";
            });
        }

        // 使用  current[0].className = current[0].className.replace(" active", "");  替换函数
    </xmp>



    <script>

        var header = document.getElementById("myDIV");
        var btns = header.getElementsByClassName("btn");

        //  循环遍历绑定点检 click 事件: 
        for (var i = 0; i < btns.length; i++) {
            btns[i].addEventListener("click", function () {
                var current = document.getElementsByClassName("active");
                current[0].className = current[0].className.replace(" active", "");
                this.className += " active";
            });
        }

        // 使用  current[0].className = current[0].className.replace(" active", "");  替换函数
    </script>

</body>

</html>